/**
 * Copyright millionhere
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may see it at...
 *      http://www.apache.org/licenses/LICENSE-2.0
 */

package info.millionhere.keepsilent;

import java.util.HashMap;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;

public class KeepSilentService extends Service {

    static final String TAG = "KeepSilentService";
    private Binder mBinder = new Binder();
    private String networkContryCallingCode;
    private String simContryCallingCode;
    
    public HashMap<String, BlackListElement> BlackList;// = new HashMap<String, BlackListElement>();

    @Override
    public IBinder onBind(Intent arg0) {
	return mBinder;
    }

    @Override
    public void onCreate() {
	Log.e(TAG, "onCreate");
	super.onCreate();
	
        SmsContent smsContent = new SmsContent(new Handler());
        MmsContent mmsContent = new MmsContent(new Handler());
        this.getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, smsContent);
        this.getContentResolver().registerContentObserver(Uri.parse("content://mms-sms"), true, mmsContent);
        
        networkContryCallingCode = DealWithCountryCallingCodes.transCountryIsoToCountryCallingCode(((TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkCountryIso());
    }

    @Override
    public void onStart(Intent intent, int startId) {
	Log.e(TAG, "onStart");
	
	BlackListXmlAdaptor BlackListXml = new BlackListXmlAdaptor();
	BlackList = BlackListXml.Read();
	
	super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
	super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
	return super.onUnbind(intent);
    }
    
    private void checkSms(){
	Log.e(TAG, "checkSms");
	
	try {
        	Cursor smsCursor = getContentResolver().query(Uri.parse("content://sms/inbox"),new String[]{"_id", "address", "read"}, " read = 0", null, "date desc"); 
        	if (smsCursor.moveToFirst()){
        	    int idColumnIndex = smsCursor.getColumnIndex("_id");
        	    int addressColumnIndex = smsCursor.getColumnIndex("address");
        	    
        	    //dummy value for setting be read statues
        	    ContentValues values = new ContentValues();
        	    values.put("read", "1");
        
        	    //set be read statues for addresses in blacklist
        	    do{
        		if (bInBlackList(smsCursor.getString(addressColumnIndex))){
        		    getContentResolver().update(Uri.parse("content://sms/inbox"), values, " _id=?", new String[]{"" + smsCursor.getInt(idColumnIndex)});
        		}
        	    }
        	    while(smsCursor.moveToNext());
        	}
	}
	catch (Exception e){}
	
	
    }
    
    private void checkMms(){
	Log.e(TAG, "checkMms");
	
	try {
	    Cursor mmsCursor = getContentResolver().query(Uri.parse("content://mms/inbox"),new String[]{"_id", "read"}, " read = 0", null, "date desc");
	    if (mmsCursor.moveToFirst()){
		int idColumnIndex = mmsCursor.getColumnIndex("_id");
		//dummy value for setting be read statues
		ContentValues values = new ContentValues();
		values.put("read", "1");
		
		do{
		    //get address by id
		    String mmsID = mmsCursor.getString(idColumnIndex);
		    
		    Cursor addressCursor = getContentResolver().query(Uri.parse("content://mms/" + mmsID + "/addr"), null, null, null, null);

		    if (addressCursor.moveToFirst()){
			int addressColumnIndex = addressCursor.getColumnIndex("address");
			
			do{
			    if (bInBlackList(addressCursor.getString(addressColumnIndex))){
				getContentResolver().update(Uri.parse("content://mms/inbox"), values, " _id=?", new String[]{"" + mmsID});
				break;
			    }
			}
			while(addressCursor.moveToNext());
		    }
		}
		//set be read statues for addresses in blacklist
		while(mmsCursor.moveToNext());
	    }
	}
	catch (Exception e){}
    }
    
    private boolean bInBlackList(String address){
	if (!DealWithCountryCallingCodes.bHaveCountryCallingCodes(address)){
	    address = networkContryCallingCode + address;
	}
	if (BlackList.containsKey(address) && BlackList.get(address).bAvailable){
	    return true;
	}
	return false;
    }
    
    class SmsContent extends ContentObserver{
	
	public SmsContent(Handler handler) {
	    super(handler);
	}
	
	@Override  
	public void onChange(boolean selfChange) {
	    super.onChange(selfChange);
	    checkSms();
	}
    }
    
    class MmsContent extends ContentObserver{
	
	public MmsContent(Handler handler) {
	    super(handler);
	}
	
	@Override  
	public void onChange(boolean selfChange) {
	    super.onChange(selfChange);
	    checkMms();
	}
    }
}
